var http = require( '../../utils/util' )
import { restDeptGetDetail, restDeptGetUserTime, restDeptGetServerUser } from '../../api/index.js'
import { restUserServerOrderSave } from '../../api/order.js'
var app = getApp()

Page({
	
  data: {
    listServerUser: [],
	index: 0,
    date: '2021-09-01',
	today: '',
    time: '12:01',
	depinfo: [],
	hasEmptyGrid: false,
	cur_year: '',
	cur_month: '',
	weeks_ch:'',
	todayIndex:'',
	display: 'none',
	times: '',
	tindex:0,
	showPrice: false
  },
  
  onLoad: function( options ) {
	var _that = this;
	options.lat = app.globalData.userLOC.latitude;
	options.lng = app.globalData.userLOC.longitude;
	options.userId = app.globalData.wxlogin.userId;
	restDeptGetDetail(options).then(res => {
		console.log(res.data);
		if(res.code == 0){
			_that.setData({
				depinfo: res.data.dept,
				//times: res.data.dept.times.split(','),
				//listServerUser: res.data.listServerUser,
				options: options,
				showPrice: res.data.showPrice
			});
			this.restDeptGetServerUser();
			//this.restDeptGetUserTime();
		}
	});
	this.setNowDate();
	
  },
  
  saveOrder: function () {
	  var _that = this;
	  
	  console.log(_that.data.tindex);
	  console.log(_that.data.times);
	  
	  if(_that.data.times.length<=0){
		  wx.showModal({
		  	content: "必须选择时间段",
		  	showCancel: false,
		  	confirmText: "确 定"
		  });
		  return;
	  }
	  
	  var time = _that.data.times[_that.data.tindex];
	  var now = new Date();
	  var today = this.data.today+" "+now.getHours()+":"+now.getMinutes();
	  var selectDay = this.data.date+" "+time.split('/')[0];
	  console.log('picker发送选择改变，携带值为1', today);
	  console.log('picker发送选择改变，携带值为2', selectDay);
	  if(new Date(today)>new Date(selectDay)){
	  	wx.showModal({
	  		content: "预约时间不能小于当前时间",
			showCancel: false,
			confirmText: "确 定"
	  	});
	  	return;
	  }
	  
	  var data = {
		  deptId: _that.data.options.deptId,
		  preDay: _that.data.date,
		  preTime: _that.data.times[_that.data.tindex],
		  price: _that.data.depinfo.price,
		  status: 1,
		  userId: app.globalData.wxlogin.userId,
		  serverUserId: _that.data.listServerUser[_that.data.index].id,
	  };
	  restUserServerOrderSave(data).then( res => {
		  console.log(res);
		  if(res.code == 0){
			  wx.showModal({
			  	content: "预约时间成功!",
			  	showCancel: false,
			  	confirmText: "确 定",
				success: function(){
					wx.redirectTo({
						url: '/pages/order/detail?id='+res.data.id
					});
				}
			  });
		  }else{
			  wx.showToast({
					  title: "稍后再试~",
					  icon: "error",
					  duration: 2000,
			  });
		  }
	  });
  },
  
  selectData: function() {
  	this.setData({
  		display: "block"
  	});
  },
  selectDataHide: function() {
  	this.setData({
  		display: "none"
  	});
	this.restDeptGetServerUser();
  },
  dateSelectAction: function (e) {
      var cur_day = e.currentTarget.dataset.idx;
      console.log(`点击的日期:${this.data.cur_year}年${this.data.cur_month}月${cur_day + 1}日`);
	  var selectDay = this.data.cur_year+"/"+this.data.cur_month+"/"+(cur_day + 1);
	  if(new Date(this.data.today)>new Date(selectDay)){
		  wx.showToast({
			  title: "不可以小于当天",
			  icon: "error",
			  duration: 2000,
		  });
		  return;
	  }
	  this.setData({
			todayIndex: cur_day,
			date: this.data.cur_year+"/"+this.data.cur_month+"/"+(cur_day + 1)
	  });
    },
   
    setNowDate: function () {
      const date = new Date();
      const cur_year = date.getFullYear();
      const cur_month = date.getMonth() + 1;
      const todayIndex = date.getDate() - 1;
      console.log(`日期：${todayIndex}`)
      const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
      this.calculateEmptyGrids(cur_year, cur_month);
      this.calculateDays(cur_year, cur_month);
	  var todayIndexD = (todayIndex+1);
      this.setData({
        cur_year: cur_year,
        cur_month: cur_month,
		date: cur_year+"/"+cur_month+"/"+todayIndexD,
		today: cur_year+"/"+cur_month+"/"+todayIndexD,
		todayZ: cur_year+""+(cur_month>=10?cur_month:'0'+cur_month)+""+(todayIndexD>=10?todayIndexD:'0'+todayIndexD),
		todayYM: cur_year+"/"+cur_month,
        weeks_ch,
        todayIndex,
      })
    },
   
    getThisMonthDays(year, month) {
      return new Date(year, month, 0).getDate();
    },
    getFirstDayOfWeek(year, month) {
      return new Date(Date.UTC(year, month - 1, 1)).getDay();
    },
    calculateEmptyGrids(year, month) {
      const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
      let empytGrids = [];
      if (firstDayOfWeek > 0) {
        for (let i = 0; i < firstDayOfWeek; i++) {
          empytGrids.push(i);
        }
        this.setData({
          hasEmptyGrid: true,
          empytGrids
        });
      } else {
        this.setData({
          hasEmptyGrid: false,
          empytGrids: []
        });
      }
    },
    calculateDays(year, month) {
		var that = this;
      let days = [];
   
      const thisMonthDays = this.getThisMonthDays(year, month);
   
      for (let i = 1; i <= thisMonthDays; i++) {
        days.push(i);
      }
   
      this.setData({
        days
      });
	  
    },
    handleCalendar(e) {
      const handle = e.currentTarget.dataset.handle;
      const cur_year = this.data.cur_year;
      const cur_month = this.data.cur_month;
      if (handle === 'prev') {
        let newMonth = cur_month - 1;
        let newYear = cur_year;
        if (newMonth < 1) {
          newYear = cur_year - 1;
          newMonth = 12;
        }
		
		if(new Date(newYear+'/'+newMonth)<new Date(this.data.todayYM)){
			return;
		}
   
        this.calculateDays(newYear, newMonth);
        this.calculateEmptyGrids(newYear, newMonth);
   
        this.setData({
          cur_year: newYear,
          cur_month: newMonth
        })
   
      } else {
        let newMonth = cur_month + 1;
        let newYear = cur_year;
        if (newMonth > 12) {
          newYear = cur_year + 1;
          newMonth = 1;
        }
   
        this.calculateDays(newYear, newMonth);
        this.calculateEmptyGrids(newYear, newMonth);
   
        this.setData({
          cur_year: newYear,
          cur_month: newMonth
        })
      }
    },
  
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
	console.log(e);
	
    this.setData({
      index: e.detail.value
    });
	this.restDeptGetUserTime();
  },
  bindDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange: function(e) {
 //    console.log('picker发送选择改变，携带值为', e.detail.value)
	// var now = new Date();
	// var today = this.data.today+" "+now.getHours()+":"+now.getMinutes();
	// var selectDay = this.data.date+" "+e.detail.value;
	// console.log('picker发送选择改变，携带值为1', today);
	// console.log('picker发送选择改变，携带值为2', selectDay);
	// if(new Date(today)>new Date(selectDay)){
	// 	wx.showToast({
	// 		title: "须大于当前时间",
	// 		icon: "error",
	// 		duration: 2000,
	// 	});
	// 	return;
	// }
 //    this.setData({
 //      time: e.detail.value
 //    })
 
 
	var time = this.data.times[e.detail.value];
	var now = new Date();
	var today = this.data.today+" "+now.getHours()+":"+now.getMinutes();
	var selectDay = this.data.date+" "+time.split('/')[0];
	console.log('picker发送选择改变，携带值为1', today);
	console.log('picker发送选择改变，携带值为2', selectDay);
	if(new Date(today)>new Date(selectDay)){
		wx.showToast({
			title: "须大于当前时间",
			icon: "error",
			duration: 2000,
		});
		return;
	}
	console.log(time);
	this.setData({
		tindex: e.detail.value,
	})
  },
  
  restDeptGetServerUser: function () {
	  var _that = this;
	  _that.setData({
	  	listServerUser: [],
		times:[]
	  });
	  var data = {
	  	deptId: _that.data.options.deptId,
	  	preDay: _that.data.date,
	  	userId: app.globalData.wxlogin.userId,
	  };
	  restDeptGetServerUser(data).then( res => {
	  	console.log(res);
	  	if(res.code == 0 && res.data.listServerUser.length>0){
			//if(res.data.listServerUser.length<=0){
				
			//}
	  		_that.setData({
	  			listServerUser: res.data.listServerUser
	  		});
			_that.restDeptGetUserTime();
	  	}else{
			
			var dateTime=new Date(_that.data.date);
			var date = new Date(dateTime.setDate( dateTime.getDate()+1) );
			var date1 = date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();
			var title =  _that.data.date+"没有可预约服务人员，切换到"+date1;
			if(res.code == -1 && res.msg != '' ) title =  res.msg+"，切换到"+date1;
			wx.showModal({
				title: title,
				icon: "error",
				confirmText: "确定",
				showCancel: false,
				success (res) {
				    if (res.confirm) {
						
				      _that.setData({
				        date: date1
				      });
				      _that.restDeptGetServerUser();
					  
				    } else if (res.cancel) {
				      console.log('用户点击取消')
				    }
				  }
			});
			
			
		}
	  });
  },

	restDeptGetUserTime: function(){
		var _that = this;
		var data = {
			deptId: _that.data.options.deptId,
			preDay: _that.data.date,
			serverUserId: _that.data.listServerUser[_that.data.index].id,
		};
		restDeptGetUserTime(data).then( res => {
			console.log(res);
			if(res.code == 0){
				_that.setData({
					times: res.data,
				});
			}else{
				var dateTime=new Date(_that.data.date);
				var date = new Date(dateTime.setDate( dateTime.getDate()+1) );
				var date1 = date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();
				wx.showModal({
					title: res.msg+"，切换到"+date1,
					icon: "error",
					confirmText: "确定",
					showCancel: false,
					success (res) {
					    if (res.confirm) {
							
					      _that.setData({
					        date: date1
					      });
					      _that.restDeptGetServerUser();
						  
					    } else if (res.cancel) {
					      console.log('用户点击取消')
					    }
					  }
				});
				
			}
		});
	},
	
	gomap: function(e) {
		console.log(e);
		var mapdata = e.target.dataset;
		const latitude = Number(mapdata.latitude);
		const longitude = Number(mapdata.longitude);
		const deptName = mapdata.deptName;
		console.log(mapdata);
		wx.openLocation({
			latitude:latitude,
			longitude:longitude,
			deptName:deptName,
			scale: 18
		});
	}




})